//
//  YBApiManager.m
//  YanzhouCloud
//
//  Created by Cocoa on 2019/7/2.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "YBApiManager.h"
#import "NSString+AES.h"
#import "NSDate+Debug.h"
//#import "MD5Encrypt.h"
//#import "RSAEncryptor.h"

//NSString * const ydd_publicKey = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCKXyxCtXCCObfoWqxZ7mw6Lsg7p8zGQ/0tScTyfKgj7DrWYbUedNDL/RvvBs/EYlvPFI35B1Nx5OuEY1o9GivbR5ZTuVQyt8zcX+iJsVdmfXfS21UdfMvaVNLLGGuP9DJhQoA6zcccALgPn4pJmLCiCQCTikwm1UODy6/wlnXHjwIDAQAB";


@interface YBApiManager ()<YBNetworkingDelegate>




@end

@implementation YBApiManager
{
    YBNetworking *_rest;
}

+ (instancetype)shareManager {
    static id apiManagerShareManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        apiManagerShareManager = [[[self class] alloc] initWithServerURL:APIHost];
    });
    return apiManagerShareManager;
}
- (instancetype)initWithServerURL:(NSString *)urlStr {
    self = [super init];
    if (self) {
        _rest = [[YBNetworking alloc] initWithBaseURL:[NSURL URLWithString:urlStr]];
        _rest.delegate = self;
        
        self.ydd_aesKey = [NSUUID.UUID.UUIDString substringToIndex:16];
        self.ydd_aesIV = [NSUUID.UUID.UUIDString substringToIndex:16];
        
    }
    return self;
}

- (RACSignal *)p_requestRefreshToken {
//    NSDictionary *param = @{@"encryptKey": [RSAEncryptor encryptString:[NSString stringWithFormat:@"%@ %@", self.ydd_aesKey, self.ydd_aesIV] publicKey:ydd_publicKey],
//                            @"refreshToken": UserManager.accessToken?:@""
//                            };
//
//    return [self sendPostRequest:@"token/initKey" param:param];
    return nil;
}
- (RACSignal *)p_requestAccessToken {
//    NSDictionary *param = @{@"refreshToken": UserManager.user.refreshToken?:@""};
//    return [self sendPostRequest:@"token/refresh" param:param];
    return nil;
}

- (RACSignal *)sendGetRequest:(NSString *)path param:(NSDictionary *)param {
    return [self sendRequest:@"GET" path:path param:param];
}
- (RACSignal *)sendPostRequest:(NSString *)path param:(NSDictionary *)param {
    return [self sendRequest:@"POST" path:path param:param];
}
- (RACSignal *)sendDeleteRequest:(NSString *)path param:(NSDictionary *)param {
    return [self sendRequest:@"DELETE" path:path param:param];
}
- (RACSignal *)sendPutRequest:(NSString *)path param:(NSDictionary *)param {
    return [self sendRequest:@"PUT" path:path param:param];
}

- (RACSignal *)sendRequest:(NSString *)method path:(NSString *)path param:(NSDictionary *)param {

    NSMutableDictionary *m_param = [NSMutableDictionary dictionaryWithDictionary:param];
    if (UserManager.shareManager.isLogin) {
        [m_param setObject:UserManager.shareManager.me.token forKey:@"token"];
    }
    
    RACSignal *signal = self.rest.call(method, path, m_param);
    return signal;
//    @weakify(self);
//   return [signal flattenMap:^__kindof RACSignal * _Nullable(id  _Nullable value) {
//
//       if ([[value objectForKey:@"status"] integerValue] == 600) {
//           ///  accessToken 失效， 请求新的token
//           UserManager.accessToken = nil;
//
//           return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
//              ///  已登录， 刷新登录accessToken
//               if (UserManager.isLogined == YES) {
//                   @strongify(self);
//                   [[self p_requestAccessToken] subscribeNext:^(id  _Nullable x) {
//
//                       NSDictionary *dataDic = [x objectForKey:@"responseData"];
//                       UserManager.accessToken = dataDic[@"accessToken"];
//                       UserManager.user.refreshToken = dataDic[@"refreshToken"];
//
//                       [self.rest.call(method, path, param) subscribeNext:^(id  _Nullable x) {
//                           [subscriber sendNext:x];
//                           [subscriber sendCompleted];
//                       } error:^(NSError * _Nullable error) {
//                           [subscriber sendError:error];
//                       }];
//
//
//                   } error:^(NSError * _Nullable error) {
//                       [subscriber sendError:[NSError errorWithDesc:@"网络错误" code:999]];
//                   }];
//
//               } else {  ///  未登录， 刷新首次token
//                   @strongify(self);
//                   [[self p_requestRefreshToken] subscribeNext:^(id  _Nullable x) {
//                       NSDictionary *dataDic = [x objectForKey:@"responseData"];
//                       UserManager.accessToken = dataDic[@"accessToken"];
//                       [self.rest.call(method, path, param) subscribeNext:^(id  _Nullable x) {
//                           [subscriber sendNext:x];
//                           [subscriber sendCompleted];
//                       } error:^(NSError * _Nullable error) {
//                           [subscriber sendError:error];
//                       }];
//
//                   } error:^(NSError * _Nullable error) {
//                       [subscriber sendError:[NSError errorWithDesc:@"网络错误" code:999]];
//                   }];
//               }
//               return nil;
//           }];
//
//       } else {
//           return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
//               if ([value[@"encrypt"] integerValue] == 1) {
//                   NSDictionary *responseData = [value objectForKey:@"responseData"];
//                   NSString *responseStr = [responseData objectForKey:@"responseData"];
//                   responseData = [[responseStr aci_decryptWithAES_AndKey:self.ydd_aesKey andIV:self.ydd_aesIV] mj_JSONObject];
//                   [value setObject:responseData forKey:@"responseData"];
//               }
//               [subscriber sendNext:value];
//               [subscriber sendCompleted];
//               return nil;
//           }];
//       }
//    }];
}

- (RACSignal *)downloadTask:(NSString *)url {
    NSString *name = [NSUUID.UUID.UUIDString stringByAppendingString:@".amr"];
    NSString *filePath = [[FileUtils documentsDirectory] stringByAppendingPathComponent:name];
    
    return [self downloadTask:url filePath:filePath];
}
- (RACSignal *)downloadTask:(NSString *)url filePath:(NSString *)filePath {
    return [self.rest download:[NSURL URLWithString:url] destination:filePath.fileToURL];
}
- (void)ybNetworking:(YBNetworking *)request didReceiveDatas:(NSDictionary *)dataDic {
    NSInteger code = [dataDic[@"code"] integerValue];
    if (code == NetworkErrorCode_TokenInvalid) {
//        [UIWindow fj_topVC].tabBarController.selectedIndex = 0;
        [[NSNotificationCenter defaultCenter] postNotificationName:notification_TokenFailed object:nil];
        [MBProgressHUD showTipMessageInWindow:@"您的登录已失效"];
    }
}

@end
